// 给小程序使用的
import getConnection from "../mysql/connection";
import * as Koa from 'koa';
import { generateSql } from "./sql";

/**
 * 增加
 * @param {*} user 
 */
export async function addUserTemp(ctx: Koa.Context, data: any)  {
  let connection: any = null;
  try {
    if (!data) return { success: false };
    const db = ctx.dbPool;
    connection = await getConnection(db);
    const sql = generateSql("user_temp", "insert", data);
    if (!sql) return { msg: "生成sql语句错误", success: false };
    await connection.execute(sql, Object.values(data));
    return { success: true };
  } catch (error) {
    return { msg: error.sqlMessage || "", success: false };
  } finally {
    if (connection) connection.release();
  }
}

/**
 * 删除
 * @param {*} id 用户ID
 */
export async function delUserTemp(ctx: Koa.Context, params: Object) {
  let connection: any = null;
  try {
    const db = ctx.dbPool;
    connection = await getConnection(db);
    const sql = generateSql("user_temp", "delete", params);
    if (!sql) return { msg: "生成sql语句错误", success: false };
    await connection.execute(sql);
    return { success: true };
  } catch (error) {
    return { msg: error.sqlMessage || "", success: false };
  } finally {
    if (connection) connection.release();
  }
}

/**
 * 更新
 * @param {*} user 
 */
export async function updateUserTemp(ctx: Koa.Context, data: any)  {
  let connection: any = null;
  try {
    if (!data?.utid && !data?.token) return { success: false };
    const db = ctx.dbPool;
    connection = await getConnection(db);
    const sql = generateSql("user_temp", "update", data);
    if (!sql) return { msg: "生成sql语句错误", success: false };
    await connection.execute(sql, Object.values(data));
    return { success: true };
  } catch (error) {
    return { msg: error.sqlMessage || "", success: false };
  } finally {
    if (connection) connection.release();
  }
}

/**
 * 查询
 * @param {*} params 查询条件
 */
export async function searchUserTemp(ctx: Koa.Context, params: Object)  {
  let connection: any = null;
  try {
    const db = ctx.dbPool;
    connection = await getConnection(db);
    const sql = generateSql("user_temp", "query", params);
    if (!sql) return { msg: "生成sql语句错误", success: false };
    const [result] = await connection.execute(sql);
    return { success: true, data: result };
  } catch (error) {
    return { msg: error.sqlMessage || "", success: false };
  } finally {
    if (connection) connection.release();
  }
}
